package com.klikmee.sms.core.web.usecases;

import java.util.ArrayList;
import com.dotexe.webframework.core.ClientApplication;
import com.dotexe.webframework.core.clientactions.MessageBox;
import com.dotexe.webframework.core.datasources.ObjectDataSource;
import com.dotexe.webframework.core.triggers.Trigger;
import com.klikmee.sms.core.base.dao.ClientDAO;
import com.klikmee.sms.core.base.util.SpringBeansLookup;
import com.klikmee.sms.core.model.Client;
import com.klikmee.sms.core.web.SmsCoreSession;
import com.klikmee.sms.core.web.service.LoginService;

public class LoginForm extends ClientApplication {

	private ObjectDataSource	dsLogin;
	private ArrayList<String>	bcLogin;

	@Override
	public void load() throws Exception {
		super.load();
		this.dsLogin = new ObjectDataSource( "dsLogin" );
		this.getDataSources().add( dsLogin );

		this.triggers.add( new Trigger( this, "btnLoginClick" ) );

		this.bcLogin = new ArrayList<String>();
		this.bcLogin.add( "Username" );
		this.bcLogin.add( "Password" );
	}

	@Override
	public void start() throws Exception {
		super.start();

		Client c = new Client();
		this.dsLogin.setSource( c );
		this.dsLogin.bind( this.bcLogin );
	}

	public void btnLoginClick() throws InstantiationException, IllegalAccessException, Exception {
		
		LoginService loginService = SpringBeansLookup.getBean( LoginService.class );
		Client clientLoginData  = (Client) this.dsLogin.getSource();
		String userName = clientLoginData.getUsername();
		String password = clientLoginData.getPassword();

		if (userName != null && password != null) {

			Client client = loginService.login( userName, password );

			if (client != null) {
				// set current client in session
				SmsCoreSession.setUser(client);
				
				
				MainForm main = this.createChildApplication( MainForm.class );
				this.showChildApp( main, "VIEWPORT" );
				main.start();
				this.hide();
				
			} else {
				MessageBox.Show( this, "Obavestenje",
						"Uneti parametri nisu ispravni!" );
				return;
			}
		} else {
			MessageBox.Show( this, "Obavestenje",
					"Uneti parametri nisu ispravni!" );
			return;
		}
	}
}